<template>
  <div class="playlistDetail" ref="playlistDetail">
    <detail-panel :image='playlist.coverImgUrl'
                  :notice='notice'
                  @pullUpLoadEvent='pullUpLoadEvent'
                  @scrollTop='scrollTop'
                  @leftClick='$router.go(-1)'
                  ref="detailPanel"
    >
      <div slot="fixedTop" class="song-top">
        <div class="play">
          <div class="icon">
            <i class="iconfont icon-bofang1"/>
          </div>
          <div class="text">
            <span>播放全部</span>
            <span>(共 {{ playlist.trackCount }} 首)</span>
          </div>
          <div class="btn">
            <van-button v-if="!playlist.subscribed" type="danger" icon="plus" round size="small" @click.native="subscribe(true)">收藏 ({{ playlist.subscribedCount }})</van-button>
            <div v-else class="collected" @click="subscribe(false)">
              <i class="iconfont icon-shoucangjia" />
              <span>{{ playlist.subscribedCount }}</span>
            </div>
          </div>
        </div>
      </div>

      <div slot="background" class="content">
        <div class="top-warpper" @click="openInfo">
          <div class="cover">
            <div class="inner">
              <span class="playCount">
                <i class="iconfont icon-icon--" />
                {{ playlist.playCount }}
              </span>
              <img :src="playlist.coverImgUrl" />
            </div>
          </div>
          <div class="info">
            <div class="inner">
              <div class="name">
                {{ playlist.name }}
              </div>
              <div class="creator" v-if="playlist.creator" v-ripple @click.stop="clickCreator">
                <img v-lazy="playlist.creator.avatarUrl" class="avatar"/>
                <span class="nickname">{{ playlist.creator.nickname }} ></span>
              </div>
              <div class="description">
                <span>{{ playlist.description }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="btn-warpper">
          <div>
            <i class="iconfont icon-pinglun" @click="toComment(playlist.id, '2', playlist)"/>
            <span>{{ playlist.commentCount }}</span>
          </div>
          <div>
            <i class="iconfont icon-fenxiang"/>
            <span>{{ playlist.shareCount }}</span>
          </div>
          <div>
            <i class="iconfont icon-xiazai"/>
            <span @click="downLoadAll">下载</span>
          </div>
        </div>
      </div>

      <play-list-cmp :list="list" @clickBtn='clickBtn' />

    </detail-panel>

    <!-- 顶部详情蒙版 -->
    <description :show.sync="showInfo"
                 :name='playlist.name'
                 :image='playlist.coverImgUrl'
                 :tags='playlist.tags'
                 :description='playlist.description'
    ></description>

    <!-- 点击歌曲弹窗 -->
    <song-popup :show.sync='showPopup'
                :song='selectSong'
                @clickItem='clickPopItem'
    ></song-popup>

    <!-- 收藏歌单弹窗 -->
    <van-dialog v-model="showCollectDialog" title="收藏到歌单" show-cancel-button confirmButtonColor='red'>
      <ul class="collect-playlist">
        <li class="item" @click="openCreateDialog">
          <div class="left">
            <i class="iconfont icon-tianjia" />
          </div>
          <div class="right">
            <span class="name">新建歌单</span>
          </div>
        </li>
        <li v-for="(playlist, index) of userPlaylist" :key="index" class="item" @click="addSongToPlaylist(playlist.id)">
          <div class="left">
            <img :src="playlist.coverImgUrl" />
          </div>
          <div class="right">
            <span class="name">{{ playlist.name }}</span>
            <span class="count">{{ playlist.trackCount }}首</span>
          </div>
        </li>
      </ul>
    </van-dialog>

    <!-- 创建歌单弹窗 -->
    <van-dialog v-model="showCreateDialog" title="新建歌单" :showConfirmButton='false' :closeOnClickOverlay='true'>
      <div class="create-dialog">
        <van-form ref="createForm" @submit="createPlaylist">
          <van-field
            v-model="createForm.name"
            maxlength="40"
            placeholder="请输入歌单标题"
            show-word-limit
            :rules="[{ required: true, message: '请输入歌单标题' }]"
          />
        <van-checkbox-group v-model="createForm.privacy">
          <van-checkbox class="checkbox" shape="square" checked-color="red" name="10">设置为隐私歌单</van-checkbox>
        </van-checkbox-group>
        <div style="margin: 16px;">
            <van-button round block type="danger" native-type="submit">
              提交
            </van-button>
          </div>
        </van-form>
      </div>
    </van-dialog>

    <van-dialog v-model="showSingerDialog" title="请选择要查看的歌手" :showConfirmButton='false' :closeOnClickOverlay='true'>
      <ul class="singer-list">
        <li v-for="(item, index) of artists" :key="index" @click="toSingerDetail(item)">{{ item.name }}</li>
      </ul>
    </van-dialog>

    <transition name="enter">
      <router-view />
    </transition>
  </div>
</template>
<script>
import DetailPanel from 'base/detail-panel'
import PlayListCmp from 'components/play-list'
import Description from 'components/description'
import SongPopup from 'components/song-popup'
import Playlist from '@/entity/PlayList'
import { detail, subscribe, create, tracks } from 'api/playlist'
import { playlist } from 'api/user'
import { downloadFile } from '@/utils'
import { mapActions } from 'vuex'

export default {
  components: {
    DetailPanel,
    PlayListCmp,
    Description,
    SongPopup
  },
  data() {
    return {
      playlist: {},
      list: [],
      top: 0,
      showInfo: false,
      notice: '',
      selectSong: null,
      showPopup: false,
      showCollectDialog: false,
      userPlaylist: [],
      showCreateDialog: false,
      createForm: {
        name: '',
        privacy: []
      },
      showSingerDialog: false,
      pageNum: 1,
      hasMore: true
    }
  },
  computed: {
    topStyle() {
      return {
        transform: `translate3d(0px, ${this.top}px, 0px)`,
      }
    },
    artists() {
      if (!this.selectSong) {
        return []
      }
      return this.selectSong.artists
    },
    headerHeight() {
      return this.$refs.detailPanel.headerHeight
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getDetail()
    })
  },
  methods: {
    getDetail() {
      const { id } = this.$route.params
      // let id = '727472445'
      if (!id) {
        this.$router.push('/')
        return
      }
      detail({ id }).then(res => {
        const { playlist, privileges } = res
        playlist.privileges = privileges
        this.playlist = new Playlist(playlist)
        this.getSongList()
      })
    },
    getSongList() {
      if (!this.hasMore) return Promise.resolve()
      return this.playlist.getSongList({
        pageSize: 100,
        pageNum: this.pageNum
      }).then(songList => {
        if (songList.length === 0) {
          this.hasMore = false
        } else {
          this.list.push(...songList)
        }
      })
    },
    pullUpLoadEvent(finish) {
      this.pageNum++
      this.getSongList().then(() => finish())
    },
    scrollTop(value) {
      this.notice = value ? this.playlist.name : ''
    },
    subscribe(type) {
      if (type) {
        this.subscribeByHttp(type)
      } else {
        const _this = this
        this.$dialog.confirm({
          message: '确定不在收藏此歌单吗？',
          confirmButtonText: '不在收藏',
          confirmButtonColor: 'red',
          beforeClose(action, done) {
            if (action === 'confirm') {
              _this.subscribeByHttp(type).finally(() => done())
            } else {
              done()
            }
          }
        })
      }
    },
    subscribeByHttp(type) {
      return subscribe({
        id: this.playlist.id,
        t: type ? 1 : 2 // 1:收藏,2:取消收藏
      }).then(() => {
        this.playlist.subscribed = type
        this.playlist.updateSubscribedCount(type ? 'add' : 'less')
      })
    },
    openInfo() {
      this.showInfo = true
    },
    clickBtn(song) {
      console.log(song)
      this.selectSong = song
      this.showPopup = true
    },
    clickPopItem(type) {
      switch (type) {
        case 'collect':
          this.onClickCollect()
          break;
        case 'singer':
          this.onClickSinger()
          break;
        case 'album':
          this.onClickAlbum()
          break;
        case 'download':
          this.download()
          break;
        case 'comment':
          this.toComment(this.selectSong.id, '0', this.selectSong)
          break;
      }
    },
    onClickCollect() {
      this.showCollectDialog = true
      const userId = localStorage.getItem('userId') || 0
      playlist(userId).then(res => {
        let { playlist } = res
        if (playlist.length > 0) {
          playlist[0].name = '我喜欢的音乐'

          playlist = playlist.filter((item, index) => {
            return index === 0 || `${item.userId}` === userId
          })
        }
        this.userPlaylist = playlist  
      }) 
    },
    openCreateDialog() {
      this.showCreateDialog = true
      this.createForm.name = this.selectSong.name
    },
    createPlaylist() {
      this.$refs.createForm.validate().then(() => {
        const { name, privacy } = this.createForm
        create(name, privacy[0]).then(res => {
          const { id, code } = res
          if (code === 200) {
            this.addSongToPlaylist(id)
          } else {
            this.$toast(res.message)
          }
        }).finally(() => {
          this.createForm.name = ''
          this.createForm.privacy = []
          this.showCreateDialog = false
        })
      })
    },
    addSongToPlaylist(pid) {
      tracks('add', pid, this.selectSong.id).then(res => {
        this.$toast(res.code === 200 ? '以收藏到歌单' : res.message)
      }).finally(() => {
        this.showCollectDialog = false
      })
    },
    onClickSinger() {
      if (this.selectSong.artists.length > 1) {
        this.showSingerDialog = true
      } else {
        this.toSingerDetail(this.artists[0])
      }
    },
    toSingerDetail(artist) {
      this.showSingerDialog = false
      this.$router.push({
        name: 'artist',
        params: {
          artistId: artist.id,
          artistName: artist.name
        }
      })
    },
    onClickAlbum() {
      this.$router.push({
        name: 'album',
        params: {
          albumId: this.selectSong.al.id
        }
      })
    },
    toComment(id, type, info) {
      this.$router.push({
        name: 'comment',
        params: {
          id,
          type,
          info
        }
      })
    },
    download() {
      const url = this.selectSong.url
      const suffix = url.substr(url.lastIndexOf('.'), url.length)
      downloadFile(url, `${this.selectSong.name}${suffix}`, {
        onDownloadProgress (progress) {
          console.log(Math.round(progress.loaded / progress.total * 100) + '%')
        }
      })
    },
    downLoadAll() {
      this.$dialog.confirm({
        message: `此歌单包含${this.playlist.trackCount}首歌,确定要下载么？`,
        showCancelButton: true,
        confirmButtonColor: 'red'
      }).then(() => {
        this.addPlayList(this.playlist)
        this.$toast('以添加下载队列')
      })
    },
    ...mapActions('downloadMgt', ['addPlayList'])
  },
  watch: {
    showInfo(value) {
      this.$refs.playlistDetail.style['z-index'] = value ? 10 : 5
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@/style/variable.less';
@import '~@/style/mixins.less';

.playlistDetail{
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: 5;
  top: 0;
  background-color: white;
  .content{
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 0 10px;
    .top-warpper{
      flex: 1;
      .cover{
        width: 35%;
        position: relative;
        .inner{
          position: absolute;
          bottom: 0;
          height: 70%;
          font-size: @font-size-small;
          img{
            width: 100%;
            height: 100%;
            border-radius: 5px;
          }
          .playCount{
            position: absolute;
            z-index: 3;
            top: 5px;
            right: 10px;
            color: white;
            >i{
              font-size: 1em;
            }
          }
        }
      }
      .info{
        width: 65%;
        height: 130px;
        color: white;
        position: relative;
        .inner{
          position: absolute;
          height: 120px;
          bottom: 0;
          padding: 0 15px;
          .name,.description,.creator{
            height: 33%;
            line-height: 1.2;
          }
          .name{
            font-size: @font-size-large;
          }
          .creator{
            display: flex;
            align-items: center;
            .avatar{
              width: 25px;
              height: 25px;
              border-radius: 50%;
            }
            .nickname{
              margin-left: 5px;
              color: #ddd;
            }
          }
          .creator,.description{
            font-size: @font-size-mini;
            color: #ddd;
          }
          .description{
            span{
              .ellipsis_2();
            }
          }
        }
      }
      .info,.cover{
        float: left;
        height: 100%;
      }
    }
    .btn-warpper{
      height: 50px;
      padding: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: white;
      >div{
        flex: 1;
        text-align: center;
        display: flex;
        flex-direction: column;
        font-size: @font-size-small;
        i{
          font-size: 1.2em;
        }
        span{
          margin-top: 5px;
        }
      }
    } 
  }
  .song-top{
    width: 100%;
    background-color: white;
    .icon{
      width: 40px;
      text-align: center;
      i{
        font-size: 1.2em;
      }
    }
    .play{
      padding: 0 10px;
      font-size: @font-size-small;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .text{
        flex: auto;
        text-align: left;
      }
      .btn{
        display: flex;
        .collected{
          font-size: @font-size-mini;
          padding-right: 10px
        }
      }
    }
  }
}
.singer-list{
  max-height: 300px;
  overflow: auto;
  >li{
    display: block;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
}

.collect-playlist{
  max-height: 300px;
  overflow-y: auto;
  padding: 0 10px;
  .item{
    display: flex;
    margin-bottom: 5px;
    .left{
      width: 40px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      i{
        font-size: 2.5em;
      }
      img{
        width: 100%;
        height: 100%;
      }
    }
    .right{
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding-left: 10px;
      flex: 1;
      width: 0;
      .name,.count{
        display: block;
        width: 100%;
        .ellipsis();
      }
      .name{
        font-size: @font-size-normal;
      }
      .count{
        margin-top: 5px;
        font-size: @font-size-small;
        color: @text-color-light;
      }
    }
  }
}
.create-dialog{
  padding: 10px;
  .checkbox{
    margin-top: 10px;
  }
}
</style>